/*
@Time : 2019/5/22 0022 16:47
@Author : visons
*/
package main

import (
	"cellent_test/proto/msg"
	"cellent_test/proto/msgid"
	"fmt"
	"gitee.com/visons/gopkg/log"
	"github.com/davyxu/cellnet"
	"github.com/davyxu/cellnet/codec"
	_ "github.com/davyxu/cellnet/codec/binary"
	_ "github.com/davyxu/cellnet/codec/gogopb"
	_ "github.com/davyxu/cellnet/codec/json"
	"github.com/davyxu/cellnet/peer"
	_ "github.com/davyxu/cellnet/peer/gorillaws"
	"github.com/davyxu/cellnet/proc"
	_ "github.com/davyxu/cellnet/proc/gorillaws"
	"github.com/gogo/protobuf/proto"
	"reflect"
	"time"
)

const (
	TestAddress = "http://127.0.0.1:18802/echo"
)

// 将消息注册到系统
func init() {
	cellnet.RegisterMessageMeta(&cellnet.MessageMeta{
		Codec: codec.MustGetCodec("gogopb"),
		Type:  reflect.TypeOf((*msg.GameHandlerREQ)(nil)).Elem(),
		ID:    int(msgid.MsgId_GameHandlerREQ),
	})
}

func main() {
	// 创建一个事件处理队列，整个服务器只有这一个队列处理事件
	queue := cellnet.NewEventQueue()

	p := peer.NewGenericPeer("gorillaws.Connector", "client", TestAddress, queue)
	p.(cellnet.WSConnector).SetReconnectDuration(time.Second)

	proc.BindProcessorHandler(p, "gorillaws.ltv", func(ev cellnet.Event) {
		ev.Session()
		switch message := ev.Message().(type) {
		case *cellnet.SessionConnected:
			log.Debugln("server connected")
			req := &msg.UserAddGoldREQ{
				Gold:     100,
				Username: "hell world",
			}

			data, err := proto.Marshal(req)
			if err != nil {
				fmt.Println("marshal fail")
			}
			ev.Session().Send(&msg.GameHandlerREQ{
				HandlerId:   msgid.GameHandlerId_UserAddGoldREQ,
				MessageData: data,
			})
			// 有连接断开
		case *cellnet.SessionClosed:
			log.Debugln("session closed: ", ev.Session().ID())
		case *msg.GameHandlerREQ:
			log.Debugf("recv: %+v %v", message, []byte("鲍勃"))

		}
	})

	// 开始侦听
	p.Start()

	// 事件队列开始循环
	queue.StartLoop()

	// 阻塞等待事件队列结束退出( 在另外的goroutine调用queue.StopLoop() )
	queue.Wait()
}
